"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: system_config.py
@DateTime: 2025/07/07
@Docs: 系统配置管理API
"""

from collections.abc import Sequence
from typing import Any, cast

from fastapi import APIRouter, Depends

from app.models import SystemConfig
from app.schemas.system import SystemConfigCreate, SystemConfigRead, SystemConfigUpdate
from app.services.system import system_config_service
from app.utils.deps import PermissionChecker

router = APIRouter()


@router.get(
    "/",
    response_model=list[SystemConfigRead],
    summary="获取所有系统配置",
    dependencies=[Depends(PermissionChecker("systemconfig:read"))],
)
async def get_all_configs() -> Sequence[SystemConfig]:
    """
    获取所有系统配置项。
    """
    configs = await system_config_service.get_active_all()
    return cast(Sequence[SystemConfig], configs)


@router.post(
    "/",
    response_model=SystemConfigRead,
    summary="创建新配置",
    dependencies=[Depends(PermissionChecker("systemconfig:create"))],
)
async def create_config(config_in: SystemConfigCreate) -> SystemConfig:
    """
    创建一个新的系统配置项。
    """
    return await system_config_service.create_config(config_in)


@router.get(
    "/{config_id}",
    response_model=SystemConfigRead,
    summary="获取单个配置",
    dependencies=[Depends(PermissionChecker("systemconfig:read"))],
)
async def get_config_by_id(config_id: int) -> SystemConfig:
    """
    根据ID获取单个系统配置项。
    """
    config = await system_config_service.get_by_id(config_id)
    return cast(SystemConfig, config)


@router.put(
    "/{config_id}",
    response_model=SystemConfigRead,
    summary="更新配置",
    dependencies=[Depends(PermissionChecker("systemconfig:update"))],
)
async def update_config(config_id: int, config_in: SystemConfigUpdate) -> SystemConfig:
    """
    更新一个系统配置项。只读配置项无法更新。
    """
    return await system_config_service.update_config(config_id, config_in)


@router.delete(
    "/{config_id}",
    response_model=dict[str, Any],
    summary="删除配置",
    dependencies=[Depends(PermissionChecker("systemconfig:delete"))],
)
async def delete_config(config_id: int) -> dict[str, Any]:
    """
    删除一个系统配置项。只读配置项无法删除。
    """
    await system_config_service.delete_config(config_id)
    return {"message": "配置删除成功"}
